<template>
  <div class="machineAlarmStatistics">
    <DFPageList ref="dfPageListRef" :page-options="pageOptions">
      <template #chart>
        <div class="chart-view">
          <div class="page-chart">
            <div class="page-chart__head">
              <div class="head-left">
                {{ $t('route.machineAlarmStatistics') }}
              </div>
            </div>
            <div class="page-chart__body">
              <v-chart class="vue-chart" autoresize :option="chartOption01" />
            </div>
          </div>
          <div class="page-chart">
            <div class="page-chart__head">
              <div class="head-left">
                {{ $t('machineAlarmStatistics.table.titleSub') }}
              </div>
            </div>
            <div class="page-chart__body">
              <v-chart class="vue-chart" autoresize :option="chartOption02" />
            </div>
          </div>
        </div>
      </template>
    </DFPageList>
  </div>
</template>

<script lang="ts" setup name="MachineAlarmStatistics">
  import { useMixins } from '@/hooks/useMixins';
  import lang from './lang';
  import { listMachine } from '@/api/base/machine';
  import { getDateStr, disablePreviousDate2 } from '@/utils/dateUtil';
  import { use } from 'echarts/core';
  import { CanvasRenderer } from 'echarts/renderers';
  import { BarChart } from 'echarts/charts';
  import { chartOptionFn_01, chartOptionFn_02 } from './chartOption';
  import VChart from 'vue-echarts';
  import {
    DatasetComponent,
    DataZoomComponent,
    GridComponent,
    LegendComponent,
    TitleComponent,
    ToolboxComponent,
    TooltipComponent,
  } from 'echarts/components';
  // import data from './data';
import { listMachineAlarmStatistics } from '@render/api/reportForm/machineAlarmStatistics';

  use([
    CanvasRenderer,
    DatasetComponent,
    DataZoomComponent,
    GridComponent,
    LegendComponent,
    TitleComponent,
    ToolboxComponent,
    TooltipComponent,
    BarChart,
  ]);

  const { loadLangFn,getDictDataListFn } = useMixins();

  loadLangFn(lang);

  const chartData_01 = ref({ legendData: [], xAxisData: [], seriesData: [] });

  const chartData_02 = ref({ legendData: [], xAxisData: [], seriesData: [] });

  const chartOption01 = computed(() => {
    const { legendData, xAxisData, seriesData } = chartData_01.value;
    const option: any = chartOptionFn_01();

    option.legend.data = legendData;
    option.xAxis.data = xAxisData;
    option.series = seriesData;

    if (seriesData.length) {
      option.yAxis.max = undefined;
    } else {
      option.yAxis.max = 1000;
    }
    return option;
  });

  const chartOption02 = computed(() => {
    const { legendData, xAxisData, seriesData } = chartData_02.value;
    const rang = seriesData.length / legendData.length;
    const option: any = chartOptionFn_02(rang ?? 1);

    option.legend.data = legendData;
    option.xAxis.data = xAxisData;
    option.series = seriesData;

    if (seriesData.length) {
      option.yAxis.max = undefined;
    } else {
      option.yAxis.max = 1000;
    }
    return option;
  });

  const dfPageListRef: any = ref(null);

  const machineList = ref([]);

  const date = ref({
    createEndTime: `${getDateStr(0)}`,
    createStartTime: `${getDateStr(-9)}`,
    defaultValue: [
      new Date(`${getDateStr(-9)}`).getTime(),
      new Date(`${getDateStr(0)}`).getTime(),
    ],
  });

  const setRequestDataFn = (e) => {
    const { entity } = e;
    entity.dateStartTime = date.value.createStartTime;
    entity.dateEndTime = date.value.createEndTime;
    delete entity.date;

    return {
      ...e,
      entity,
    };
  };

  const beforeResetFn = () => {
    date.value.createStartTime = `${getDateStr(-9)}`;
    date.value.createEndTime = `${getDateStr(0)}`;
  };

  const pageOptions = {
    searchForm: {
      formSchemas: [
        {
          label: 'machineName',
          prop: 'machineCodeList',
          component: 'NSelect',
          options: machineList,
          componentProps: {
            multiple: true,
          },
        },
        {
          label: 'date',
          common: true,
          component: 'NDatePicker',
          defaultValue: date.value.defaultValue,
          componentProps: {
            clearable: false,
            type: 'daterange',
            valueFormat: 'yyyy-MM-dd',
            format: 'yyyy-MM-dd',
            defaultTime: ['00:00:00', '23:59:59'],
            isDateDisabled: disablePreviousDate2,
            onUpdateValue: (_, v: string[]) => {
              if (v) {
                date.value.createStartTime = v[0];
                date.value.createEndTime = v[1];
              } else {
                date.value.createStartTime = '';
                date.value.createEndTime = '';
              }
            },
          },
        },
      ],
      beforeResetFn,
      requestFn: async(data) => {
        const newData = setRequestDataFn(data);

        const res = await listMachineAlarmStatistics(newData);

        const [data_01, data_02] = parseChartData(res.data || []);

        chartData_01.value = data_01;

        chartData_02.value = data_02;

        console.log(res);
      },
    },
    table: {
      noTable: true,
      afterSlotName: 'chart',
    },
  };

  const alarmTypeList = ref([]);

  const initDictData = async () => {
    const res = await Promise.all([listMachine(),getDictDataListFn('alarm_type'),]);

    const [res2,res3] = res;

    machineList.value =
      res2?.data.map((item) => ({ label: item.machineName, value: item.machineCode })) || [];

    alarmTypeList.value = res3 || [];

    console.log(res3)

    nextTick(() => {
      dfPageListRef.value?.reloadTableFn();
    });
  };

  initDictData();

  function parseChartData(rows) {
    const rowData = rows[0]?.data || [];
    const alarmVos = rowData[0]?.alarmVos || [];

    const xAxisData = rows.map((row) => row.date) || [];

    const legendData_01 = rowData.map((row) => row.machineName) || [];
    const legendData_02 = alarmVos.map((row) => {
      return alarmTypeList.value.find(item=>item.value == row.alarmType)?.label || '';
    }) || [];

    const seriesData_01 = rowData.map((row, i) => {
      const data = rows.map(({ data }) => {
        return data[i].count;
      });
      return {
        name: row.machineName,
        type: 'bar',
        data,
      };
    });

    const seriesData_02 = rowData.reduce((previous, current, i) => {
      const alarmList = current.alarmVos.map((item, j) => {
        const data = rows.map(({ data }) => {
          return {
            name: item.machineName,
            value: data[i].alarmVos[j].count,
          };
        });

        return {
          type: 'bar',
          name: alarmTypeList.value.find(aItem=>aItem.value == item.alarmType)?.label || '',
          stack: item.machineCode,
          data,
        };
      });
      return [...previous, ...alarmList];
    }, []);
    return [
      { xAxisData, legendData: legendData_01, seriesData: seriesData_01 || [] },
      { xAxisData, legendData: legendData_02, seriesData: seriesData_02 || [] },
    ];
  }

  // nextTick(() => {
  //   const [data_01, data_02] = parseChartData(data || []);
  //   chartData_01.value = data_01;
  //   chartData_02.value = data_02;
  // });
</script>

<style lang="less" scoped>
  .machineAlarmStatistics {
    .chart-view {
      width: 100%;
    }
    .page-chart {
      margin-top: 16px;
      border-radius: 2px;
      // padding: 24px 24px 48px;
      background: #fff;
      &__head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 44px;
        .head-left {
          font-size: 16px;
          font-weight: 500;
          color: #222;
        }
      }
    }
    .vue-chart {
      width: 100%;
      height: 340px;
    }
  }
</style>
